#!/bin/bash
# HackerPermKeeper T00ls - Linux环境快速测试脚本
# 使用方法: ./quick_test_linux.sh <目标IP> [攻击机IP]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置参数
TARGET_IP=${1:-"192.168.1.200"}
ATTACKER_IP=${2:-"192.168.1.100"}
PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
LOG_FILE="$PROJECT_ROOT/logs/quick_test_$(date +%Y%m%d_%H%M%S).log"

# 创建日志目录
mkdir -p "$PROJECT_ROOT/logs"

# 日志函数
log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

success() {
    echo -e "${GREEN}✅ $1${NC}" | tee -a "$LOG_FILE"
}

error() {
    echo -e "${RED}❌ $1${NC}" | tee -a "$LOG_FILE"
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}" | tee -a "$LOG_FILE"
}

# 检查依赖
check_dependencies() {
    log "检查系统依赖..."
    
    local deps=("python3" "nmap" "curl" "ping")
    for dep in "${deps[@]}"; do
        if command -v "$dep" >/dev/null 2>&1; then
            success "$dep 已安装"
        else
            error "$dep 未安装，请先安装: sudo apt install $dep"
            exit 1
        fi
    done
}

# 检查网络连通性
check_network() {
    log "检查网络连通性..."
    
    if ping -c 3 "$TARGET_IP" >/dev/null 2>&1; then
        success "目标机 $TARGET_IP 网络可达"
    else
        error "目标机 $TARGET_IP 网络不可达"
        exit 1
    fi
}

# 快速端口扫描
quick_scan() {
    log "执行快速端口扫描..."
    
    local scan_result
    scan_result=$(nmap -sS -O -sV --top-ports 1000 "$TARGET_IP" 2>/dev/null || echo "扫描失败")
    
    if [[ "$scan_result" == *"22/tcp"* ]]; then
        success "发现SSH服务 (22/tcp)"
    fi
    
    if [[ "$scan_result" == *"80/tcp"* ]] || [[ "$scan_result" == *"443/tcp"* ]]; then
        success "发现Web服务"
    fi
    
    if [[ "$scan_result" == *"21/tcp"* ]]; then
        success "发现FTP服务 (21/tcp)"
    fi
    
    echo "$scan_result" >> "$LOG_FILE"
}

# 测试自动决策系统
test_auto_decision() {
    log "测试自动决策系统..."
    
    cd "$PROJECT_ROOT"
    
    if [[ -f "apps/auto_decision_main.py" ]]; then
        python3 apps/auto_decision_main.py --target "$TARGET_IP" --mode scan --quick 2>&1 | tee -a "$LOG_FILE"
        if [[ ${PIPESTATUS[0]} -eq 0 ]]; then
            success "自动决策系统扫描完成"
        else
            warning "自动决策系统扫描出现问题"
        fi
    else
        warning "未找到自动决策主程序"
    fi
}

# 测试后门检查功能
test_backdoor_check() {
    log "测试后门检查功能..."
    
    cd "$PROJECT_ROOT"
    
    if [[ -f "payload/13check/backdoor_checks.py" ]]; then
        python3 payload/13check/backdoor_checks.py --target "$TARGET_IP" --quick-check 2>&1 | tee -a "$LOG_FILE"
        if [[ ${PIPESTATUS[0]} -eq 0 ]]; then
            success "后门检查功能正常"
        else
            warning "后门检查功能出现问题"
        fi
    else
        warning "未找到后门检查程序"
    fi
}

# 测试SSH连接
test_ssh_connection() {
    log "测试SSH连接功能..."
    
    # 尝试常见的弱密码
    local common_passwords=("root" "admin" "password" "123456" "toor")
    local common_users=("root" "admin" "user" "test")
    
    for user in "${common_users[@]}"; do
        for pass in "${common_passwords[@]}"; do
            if sshpass -p "$pass" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$user@$TARGET_IP" "echo 'SSH连接成功'" 2>/dev/null; then
                success "发现弱密码: $user:$pass"
                return 0
            fi
        done
    done
    
    warning "未发现明显的SSH弱密码"
}

# 测试Web漏洞扫描
test_web_scan() {
    log "测试Web漏洞扫描..."
    
    local web_ports=("80" "443" "8080" "8443")
    
    for port in "${web_ports[@]}"; do
        if curl -s --connect-timeout 5 "http://$TARGET_IP:$port" >/dev/null 2>&1; then
            success "发现Web服务在端口 $port"
            
            # 简单的目录扫描
            local common_paths=("/admin" "/login" "/test" "/phpmyadmin" "/wp-admin")
            for path in "${common_paths[@]}"; do
                local response
                response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "http://$TARGET_IP:$port$path")
                if [[ "$response" == "200" ]]; then
                    success "发现可访问路径: $path"
                fi
            done
        fi
    done
}

# 生成测试报告
generate_report() {
    log "生成测试报告..."
    
    local report_file="$PROJECT_ROOT/reports/quick_test_report_$(date +%Y%m%d_%H%M%S).md"
    mkdir -p "$PROJECT_ROOT/reports"
    
    cat > "$report_file" << EOF
# HackerPermKeeper T00ls 快速测试报告

## 测试信息
- **测试时间**: $(date '+%Y-%m-%d %H:%M:%S')
- **目标IP**: $TARGET_IP
- **攻击机IP**: $ATTACKER_IP
- **测试类型**: 快速功能验证

## 测试结果摘要
$(grep -E "(✅|❌|⚠️)" "$LOG_FILE" | tail -20)

## 详细日志
详细测试日志请查看: $LOG_FILE

## 建议
1. 如果发现弱密码，建议立即修改
2. 如果发现开放的Web服务，建议进行深度安全检查
3. 建议定期运行完整的安全扫描

---
*报告由 HackerPermKeeper T00ls 自动生成*
EOF

    success "测试报告已生成: $report_file"
}

# 主函数
main() {
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║              HackerPermKeeper T00ls 快速测试                 ║"
    echo "║                     Linux环境版本                           ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    log "开始快速测试 - 目标: $TARGET_IP"
    
    # 执行测试步骤
    check_dependencies
    check_network
    quick_scan
    test_auto_decision
    test_backdoor_check
    test_ssh_connection
    test_web_scan
    generate_report
    
    echo -e "${GREEN}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                      测试完成！                             ║"
    echo "║                                                              ║"
    echo "║  详细日志: $LOG_FILE"
    echo "║  测试报告: $PROJECT_ROOT/reports/"
    echo "║                                                              ║"
    echo "║  如需完整测试，请参考: docs/LINUX_AUTOMATION_TEST_GUIDE.md  ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# 脚本入口
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi